package com.fzy.core.entity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.fzy.core.utils.StringUtils;

public class PCDEntry {

	String name;

	String code;

	String parentCode;

	List children;
	
	public List getChildren() {
		return children;
	}

	public void setChildren(List children) {
		this.children = children;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getParentCode() {
		return parentCode;
	}

	public void setParentCode(String parentCode) {
		this.parentCode = parentCode;
	}
	
	
	public static String convertEntryListToJson(List entryList) {
		if (entryList == null)
			return null;
		String result = "[";
		for (Iterator iter = entryList.iterator(); iter.hasNext();) {
			PCDEntry e = (PCDEntry) iter.next();
			if (StringUtils.isBlank(e.getCode()))
				continue;
			result += "{";
			result += "\"code\" : \"" + e.getCode() + "\"";
			result += ", \"name\" : \"" + e.getName() + "\"";
			if (!StringUtils.isBlank(e.getParentCode()))
				result += ", \"parentCode\" : \"" + e.getParentCode() + "\"";
			if (e.getChildren() != null && e.getChildren().size() > 0)
				result += ", \"list\" : "
						+ convertEntryListToJson(e.getChildren());
			result += "}";
			if (iter.hasNext())
				result += ", ";
		}
		result += "]";
		return result;
	}

	/**
	 * 装配父条目和子条目

	 * 
	 * @param parents
	 * @param children
	 * @return
	 */
	public static List assembleEntry(List parents, List children) {
		if (children == null)
			return parents;
		Object[] x = children.toArray();
		Object[] y = parents.toArray();
		for (int i = 0; i < x.length; i++) {
			PCDEntry entry = (PCDEntry) x[i];
			if (StringUtils.isBlank(entry.getCode())
					|| StringUtils.isBlank(entry.getParentCode())) {
				continue;
			}
			PCDEntry parentEntry = getEntryByCode(entry.getParentCode(), y);
			if (parentEntry == null)
				continue;
			if (parentEntry.getChildren() == null)
				parentEntry.setChildren(new ArrayList());
			parentEntry.getChildren().add(entry);
		}
		return parents;
	}

	/**
	 * 根据id找到字典条目
	 * 
	 * @param id
	 * @param entryList
	 * @return
	 */
	public static PCDEntry getEntryByCode(String code, Object[] entries) {
		for (int i = 0; i < entries.length; i++) {
			PCDEntry e = (PCDEntry) entries[i];
			if (code.equals(e.getCode())) {
				return e;
			}
		}
		return null;
	}
}
